/**
 *  @description 使用 svg-captcha 生成 图形校验码
 * @author mosaic
 */

import svgCaptcha from 'svg-captcha'
import redis from './redis.js'
import crypto from 'crypto';
import { v4 as uuidv4 } from 'uuid'; // 使用命名导入

/**
 *
 * @description 生成 图形验证码
 * @return {*}
 */
export const generateCaptcha = async (ctx, temToken) => {
  //  若创建算数式验证码，将create改为createMathExpr
  const newCaptcha = svgCaptcha.createMathExpr({
    size: 4,
    ignoreChars: '0o1i',
    fontSize: 50,
    noise: 2,
    width: 120,
    height: 35,
    color: 'true', // 红色字符
    mathMin: 0,
    mathMax: 9,
    charPreset: 'true',
    background: '' // 白色背景
  });

  // 存储验证码
  await redis.set(`captcha:${temToken}`, newCaptcha.text, 300);
  // redis.get(`captcha:${temToken}`)
  return {
    data: newCaptcha.data,
    // token: `captcha:${temToken}`
  }
}

export const verifyCaptcha = async (ctx) => {
  let result = {};
  const { consequence, temToken } = ctx.request.body;
  if (!consequence) { result = { code: 400, msg: '缺少参数值consequence' }; }
  if (!temToken) { result = { code: 400, msg: '缺少参数值temToken' }; }
  const exists = await redis.exists(`captcha:${temToken}`)
  if (exists === 1) {
    const val = await redis.get(`captcha:${temToken}`)
    const accessToken = uuidv4();  // v4() 生成一个随机的 UUID
    await redis.set(`access:${accessToken}`, accessToken, 120); // 2分钟有效期
    if (val == consequence) { result = { code: 200, msg: 'ok', data: accessToken }; }
    else {
      result = { code: 400, msg: '图形验证码结果不正确' };
    }
  } else {
    result = { code: 400, msg: '请刷新图形验证码再尝试!' };
  }
  redis.del(`captcha:${temToken}`);// 校验过则清空当前key
  return result;
}

export const temporaryToken = async ({ query }) => {
  let deviceId = query.deviceId
  const hex = crypto.randomBytes(8).toString('hex'); // 64 字符
  return deviceId + hex;
}



